package edu.sdbi.judge.domain.vo;

import lombok.Data;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
public class TreeNode<T> {

    private String id;

    private String name;

    private T data;

    private List<TreeNode<T>> children;

    public static <T> List<TreeNode<T>> createTree(
            List<T> list, Class<T> tClass,
            String idFieldStr, String nameFieldStr, String pidFieldStr)
            throws NoSuchFieldException, IllegalAccessException {
        Field idField = tClass.getDeclaredField(idFieldStr);
        Field nameField = tClass.getDeclaredField(nameFieldStr);
        Field pidField = tClass.getDeclaredField(pidFieldStr);
        idField.setAccessible(true);
        nameField.setAccessible(true);
        //构造<id, 实体>映射关系
        Map<String, TreeNode<T>> map = new HashMap<>();
        map.put("-1", new TreeNode<>());
        //创建TreeNode对象，映射关系
        for (T t : list) {
            String id = idField.get(t).toString();
            String name = nameField.get(t).toString();
            TreeNode<T> node = new TreeNode<>();
            node.setId(id);
            node.setName(name);
            node.setData(t);
            map.put(id, node);
        }
        //每个节点挂载到父节点下
        for (TreeNode<T> node : map.values()) {
            T t = node.getData();
            String pid = pidField.get(t).toString();
            TreeNode<T> parentNode = map.get(pid);
            if (parentNode != null) {
                List<TreeNode<T>> children = parentNode.getChildren();
                if (children == null) {
                    children = new ArrayList<>();
                    parentNode.setChildren(children);
                }
                children.add(node);
            }
        }
        return map.get("-1").getChildren();
    }

}
